package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author 42
 * @date 2025/4/5
 * @Description
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单:{}",new Date());

        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
        // select * from orders where status = 1 and order_time < 当前时间-15分钟
        List<Orders> info = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,dateTime);

        if(info!=null && info.size()>0){
            info.forEach(x->{
                x.setCancelTime(LocalDateTime.now());
                x.setCancelReason("支付超时，自动取消");
                x.setStatus(Orders.CANCELLED);
                orderMapper.update(x);
            });
        }


    }

    /**
     * 处理派送中状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliverOrder(){
        log.info("处理派送中订单:{}",new Date());
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, dateTime);
        if(list!=null && list.size()>0){
            list.forEach(x->{
                x.setStatus(Orders.CANCELLED);
                orderMapper.update(x);
            });
        }

    }


}
